/**
 * 
 */
package com.miyake.loveviewweb.client.main;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.Key;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.miyake.loveviewweb.client.DataServiceListener;
import com.miyake.loveviewweb.client.DataServiceWrapper;
import com.miyake.loveviewweb.client.account.GoogleLogin;
import com.miyake.loveviewweb.client.account.LoginListener;
import com.miyake.loveviewweb.client.community.CommunityMainUI;
import com.miyake.loveviewweb.client.community.UserPropertyPanel;
import com.miyake.loveviewweb.client.dialog.BasicDialog;
import com.miyake.loveviewweb.client.dialog.UploadDialog;
import com.miyake.loveviewweb.client.explorer.BasicExplorerUI;
import com.miyake.loveviewweb.client.service.DataService;
import com.miyake.loveviewweb.client.viewer.DataDialogCreator;
import com.miyake.loveviewweb.client.viewer.FolderDialogCreator;
import com.miyake.loveviewweb.client.viewer.PluginDialogFactory;
import com.miyake.loveviewweb.client.viewer.PluginDialogFactory.ChartHandler;
import com.miyake.loveviewweb.client.viewer.Viewer;
import com.miyake.loveviewweb.client.viewer.ViewerFactory;
import com.miyake.loveviewweb.client.viewer.DataDialogCreator.EditType;
import com.miyake.loveviewweb.client.viewer.FolderDialogCreator.FolderType;
import com.miyake.loveviewweb.shared.model.ChartModel;
import com.miyake.loveviewweb.shared.model.DataColumnModel;
import com.miyake.loveviewweb.shared.model.DataModel;
import com.miyake.loveviewweb.shared.model.FolderModel;
import com.miyake.loveviewweb.shared.model.UserModel;
import com.miyake.loveviewweb.shared.model.ChartModel.ChartEngine;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.TabBar;

/**
 * @author a1199022
 *
 */
public class MainUI extends Composite implements IMainUI {
    HTMLPanel mainPanel = new HTMLPanel("");
    HorizontalPanel loginPanel = new HorizontalPanel();
    
    TabBar tabBar =  new TabBar();
    protected Viewer viewer;
    private SimplePanel menuPanel;
    private SplitLayoutPanel splitPanel;
    private CommunityMainUI communityPanel;
    private TopMainUI profilePanel;
    private UserPropertyPanel userProertyPanel;
    
    /**
     * Because this class has a default constructor, it can
     * be used as a binder template. In other words, it can be used in other
     * *.ui.xml files as follows:
     * <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
     *   xmlns:g="urn:import:**user's package**">
     *  <g:**UserClassName**>Hello!</g:**UserClassName>
     * </ui:UiBinder>
     * Note that depending on the widget that is used, it may be necessary to
     * implement HasHTML instead of HasText.
     */
    public MainUI() {
        initWidget(mainPanel);
        initialize();
    }

    public MainUI(String firstName) {
        initWidget(mainPanel);
        initialize();
    }

    private void initialize() {
        mainPanel.setWidth("100%");
        mainPanel.setHeight("100%");
        mainPanel.add(loginPanel);
        loginPanel.setWidth("100%");

        createLogin();
        createTab();
        
        createDataManage();
    }

    private void createTab() {
        tabBar.addTab("Top");
        tabBar.addTab("My Data");
        tabBar.addTab("Community");
        tabBar.addTab("Setting");
        
        tabBar.selectTab(1);
        
        mainPanel.add(tabBar);
        tabBar.addSelectionHandler(new SelectionHandler<Integer>() {
            public void onSelection(SelectionEvent<Integer> event) {
                if (event.getSelectedItem().equals(0)) {
                    setMyDataVisible(false);
                    setCommunityVisible(false);
                    setTopVisible(true);
                    setMyProfileVisible(false);
                }
                else if(event.getSelectedItem().equals(1)) {
                    setMyDataVisible(true);
                    setCommunityVisible(false);
                    setTopVisible(false);
                    setMyProfileVisible(false);
                }
                else if (event.getSelectedItem().equals(2)) {
                    setMyDataVisible(false);
                    setCommunityVisible(true);
                    setTopVisible(false);
                    setMyProfileVisible(false);
                }
                else if (event.getSelectedItem().equals(3)) {
                    setMyDataVisible(false);
                    setCommunityVisible(false);
                    setTopVisible(false);
                    setMyProfileVisible(true);
                }               
            }
        });
    }


    protected void setMyProfileVisible(boolean b) {
        if (userProertyPanel == null && b) {
            DataService.Util.getInstance().getMyProperty(new AsyncCallback<UserModel>() {

                public void onFailure(Throwable caught) {
                }

                public void onSuccess(UserModel result) {
                    userProertyPanel = new UserPropertyPanel(result, true);
                    mainPanel.add(userProertyPanel);
                }
                
            });

        }
        userProertyPanel.setVisible(b);
    }

    protected void setTopVisible(boolean b) {
        if (profilePanel == null && b) {
            profilePanel = new TopMainUI();
            mainPanel.add(profilePanel);
        }
        if (profilePanel != null) {
            profilePanel.setVisible(b);
        }
    }

    protected void setCommunityVisible(boolean b) {
        if (communityPanel == null && b) {
            communityPanel = new CommunityMainUI();
            mainPanel.add(communityPanel);
        }
        if (communityPanel != null) {
            communityPanel.setVisible(b);
        }
    }

    private void createDataManage() {
        menuPanel = new SimplePanel();
        splitPanel = new SplitLayoutPanel();
        ScrollPanel verticalPanelLeft = new ScrollPanel();
        final ScrollPanel verticalPanelRight = new ScrollPanel();
        
        mainPanel.add(menuPanel);
        mainPanel.add(splitPanel);
        splitPanel.addWest(verticalPanelLeft, 200.0);

        splitPanel.add(verticalPanelRight);
        splitPanel.setWidth("100%");
        splitPanel.setHeight("85%");
        verticalPanelLeft.setWidth("100%");
        verticalPanelLeft.setHeight("100%");
        verticalPanelLeft.setStylePrimaryName("explorer");
        verticalPanelRight.setHeight("100%");
        verticalPanelRight.setWidth("100%");
        verticalPanelRight.setStylePrimaryName("mainview");
        
        final DataServiceWrapper serviceWrapper = DataServiceWrapper.getInstance();
        final BasicExplorerUI explorer = new BasicExplorerUI();        
        final UiDataHandler uiHandler = new UiDataHandler() {

            public void createRootFolder() {
                new FolderDialogCreator(FolderType.ROOT_FOLDER).show("Root Folder");
            }

            public void createFolder() {
                new FolderDialogCreator(FolderType.SUB_FOLDER).show("Folder");
            }

            public void createData() {
                new DataDialogCreator(EditType.CREATE).show("Data");
            }

            public void createChart(final DataModel dataModel) {
                List<String> list = new ArrayList<String>();
                for (DataColumnModel c : dataModel.getXyDataBody().getDataColumn()) {
                    list.add(c.getHeader());
                }
                
                PluginDialogFactory.getInstance().createChart(new ChartHandler() {

                    public void onSelect(Key pluginKey,
                            Map<String, String> column) {

                        String name = "Chart";
                        serviceWrapper.createChart(name, dataModel.getKey(), column, ChartEngine.PLUGIN_CHART, pluginKey); 
                    }

                }, dataModel);
                
/*                new BasicDialog(new ChartDialogPanel("Chart", list, dataModel)) {

                    @Override
                    protected void onOK(Composite composite) {
                        ChartDialogPanel panel = ((ChartDialogPanel)composite);
                        String name = panel.getText();
                        Integer x = panel.getSelectedIndexX();
                        Integer y = panel.getSelectedIndexY();
                        if (panel.getSelectedChartPlugin() != null) {
                            serviceWrapper.createChart(name, dataModel.getKey(), x, y, 
                                ChartEngine.PLUGIN_CHART, panel.getSelectedChartPlugin().getKey());           
                        }
                        else {
                            serviceWrapper.createChart(name, dataModel.getKey(), x, y, 
                                ChartEngine.DEFAULT_FLASH_CHART, null);
                        }
                    }
                    
                }.showDialog();*/
            }

            public void delete() {
                serviceWrapper.delete(serviceWrapper.getSelectedKey());
            }

            public void upload() {
                new BasicDialog(new UploadDialog("", "upload")) {

                    @Override
                    protected boolean isOkVisible() {
                        return false;
                    }

                    @Override
                    protected void onOK(Composite composite) {
                        explorer.rebuild();
                    }
                    
                }.showDialog();

            }


            public void pluginMarket() {
                Window.open(GWT.getHostPageBaseURL() + "?startup=pluginMarket", "_blank", "");
            }

            public void pluginProvider() {
                Window.open(GWT.getHostPageBaseURL()+"?startup=pluginProvider", "_blank", "");
            }
            
        };
        
        serviceWrapper.addDataServiceListener(new DataServiceListener() {

            public void onCreateRootFolder(FolderModel folder) {
            }

            public void onCreateFolder(FolderModel folder, FolderModel parent) {
            }

            public void onCreateData(DataModel data, FolderModel parent) {
            }

            public void onSelectChange(Object object, FolderModel folder) {
                verticalPanelRight.clear();
                Key key = null;
                if (object.getClass().equals(FolderModel.class)) {
                    viewer = ViewerFactory.getInstance().createFolderViewer(DataServiceWrapper.getInstance().getSelectedFolder(), uiHandler);
                    verticalPanelRight.add(viewer);
                    key = ((FolderModel)object).getKey();
                }
                else if (object.getClass().equals(ChartModel.class)) {
                }
                else if (object.getClass().equals(DataModel.class)) {
                    viewer = ViewerFactory.getInstance().createDataViewer(DataServiceWrapper.getInstance().getSelectedData(), uiHandler);
                    verticalPanelRight.add(viewer);
                    key = ((DataModel)object).getKey();
                }
                viewer.update(key);
            }

            public void onCreateChart(ChartModel chart, DataModel parent) {
                viewer.update(chart.getKey());
            }

            public void onDelete(Key key) {
                viewer.update(key);
            }

            public void onUpdateData(Key data) {
                viewer.update(data);
            }

            public void onUpdatFolder(Key key) {
                viewer.update(key);
            }
            
        });
        
        menuPanel.add(new DesktopMenu(uiHandler));
        verticalPanelLeft.add(explorer);
    }

    
    private void createLogin() {
        loginPanel.add(new GoogleLogin(new LoginListener() {
            public void onLogin(boolean login) { 
            }

            public void onRequestLogin(String url) { 
            }
            
        }, GWT.getHostPageBaseURL()));
    }
    
    /* (non-Javadoc)
     * @see com.miyake.loveviewweb.client.main.IMainUI#setLoginWidget(com.google.gwt.user.client.ui.Widget)
     */
    public void setLoginWidget(Widget login) {
        this.loginPanel.add(login);
    }

    public Widget getUiWidget() {
        return this;
    }

    private void setMyDataVisible(boolean visible) {
        if (visible == true && menuPanel == null) {
            createDataManage();
        }
        if (menuPanel != null) {
            menuPanel.setVisible(visible);
            splitPanel.setVisible(visible);
        }
    }
}
